package main

import (
	"net"
	"net/http"
	"runtime/debug"
	"time"

	"face_search/src/handler"
	"face_search/src/scheduler"

	"github.com/pochard/logrotator"
	"github.com/sirupsen/logrus"
)

func main() {
	defer func() {
		if info := recover(); info != nil {
			logrus.Error("系统出现严重异常：", info, string(debug.Stack()))
		}
	}()

	writer, err := logrotator.NewTimeBasedRotator("logs/face-%Y%m%d.log", 24*time.Hour)
	if err != nil {
		logrus.Error("%v\n", err.Error())
	}
	defer writer.Close()
	logrus.SetOutput(writer)
	logrus.SetLevel(4)

	cleaner, clrErr := logrotator.NewTimeBasedCleaner("logs/*.log", 7*24*time.Hour)
	if clrErr != nil {
		logrus.Error(clrErr.Error())
	}

	t1 := time.NewTicker(time.Hour * 5)
	go func(ticker interface{}) {
		for {
			select {
			case <-ticker.(*time.Ticker).C:
				cleaner.Clean()
				scheduler.DirDelScheduler("./image/")
			}
		}
	}(t1)

	listener, listenErr := net.Listen("tcp", ":8090")
	if listenErr != nil {
		logrus.Fatalf("端口异常: %v", listenErr)
	}
	mux := initRouter()
	httpServer := &http.Server{
		ReadTimeout:  100 * time.Second,
		WriteTimeout: 100 * time.Second,
		Handler:      mux,
	}
	logrus.Info("enjoy it......")
	startErr := httpServer.Serve(listener)
	if startErr != nil {
		logrus.Fatalf("启动服务异常: %v", startErr)
	}
}

func initRouter() *http.ServeMux {
	mux := http.NewServeMux()
	mux.HandleFunc("/getface", handler.OpencvCutImage)
	return mux
}
